package cn.xshi.oauth.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.xshi.common.entity.OauthAccountEntity;
import cn.xshi.common.entity.UserInfoEntity;
import cn.xshi.common.util.Base64Util;
import cn.xshi.common.util.FastJsonUtils;
import cn.xshi.common.util.StringUtil;
import cn.xshi.oauth.model.OauthAccount;
import cn.xshi.oauth.service.OauthAccountService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.xshi.common.annotation.Auth;
import cn.xshi.common.base.BaseAction;
import cn.xshi.common.base.BasePage;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.base.BaseSearch;
import cn.xshi.common.entity.UserParamInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Desc 授权中心账户
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
@RestController
@RequestMapping("/oauthAccount")
@Api(value = "授权中心账户API",tags = "授权中心账户API",description = "授权中心账户API")
public class OauthAccountController extends BaseAction {

    @Resource
    private OauthAccountService oauthAccountService;

    /**
     * 查询账户集合并分页
     * @param baseSearch
     */
    @ApiOperation(value="查询账户集合并分页", notes="分页查找")
    @PostMapping(value="/list")
    @Auth(value = "/oauthAccount/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BasePage<List<OauthAccount>> getOauthAccountListByCondition(@RequestBody BaseSearch baseSearch){
        Map<String, Object> condition = baseSearch.convert();
        commonHPager(baseSearch);
        List<OauthAccount> oauthAccountList = oauthAccountService.getOauthAccountList(condition);
        PageInfo<OauthAccount> page = new PageInfo<OauthAccount>(oauthAccountList);
        return outPageBootStr(page,baseSearch);
    }

    /**
     * 查询单个账户
     * @param id
     */
    @ApiOperation(value="查询单个账户", notes="根据账户id查找")
    @GetMapping(value="/get/{id}")
    @Auth(value = "/oauthAccount/get",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult<OauthAccount> getOauthAccountById(@PathVariable("id")String id){
        OauthAccount oauthAccount = oauthAccountService.getOauthAccountById(id);
        if(!StringUtil.isEmpty(oauthAccount.getCreateId())){
            OauthAccountEntity createBy = getAccount(oauthAccount.getCreateId());
            if(null != createBy){
                oauthAccount.setCreateBy(createBy.getName());
            }
        }
        if(!StringUtil.isEmpty(oauthAccount.getUpdateId())){
            OauthAccountEntity modifiedBy = getAccount(oauthAccount.getUpdateId());
            if(null != modifiedBy){
                oauthAccount.setModifiedBy(modifiedBy.getName());
            }
        }
        return outDataStr(oauthAccount);
    }

    /**
     * 添加
     * @param oauthAccount
     */
    @ApiOperation(value="新增账户", notes="创建账户根据相关资料")
    @PostMapping(value="/add")
    public BaseResult addOauthAccount(@RequestBody OauthAccount oauthAccount){
        int i = 0;
        if(null != oauthAccount){
            i=oauthAccountService.addOauthAccount(oauthAccount);
        }
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     * 修改
     * @param oauthAccount
     */
    @ApiOperation(value="编辑账户", notes="编辑账户根据相关资料")
    @PutMapping(value="/update")
    public BaseResult updateOauthAccount(@RequestBody OauthAccount oauthAccount){
        int i = 0;
        if(null != oauthAccount){
            i=oauthAccountService.updateOauthAccount(oauthAccount);
        }
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     * 冻结
     * @param id
     */
    @ApiOperation(value="冻结账户", notes="冻结账户")
    @DeleteMapping(value="/freeze/{id}")
    @Auth("/oauthAccount/freeze")
    public BaseResult freezeAccount(@PathVariable("id")String id){
        int i = 0;
        if(!StringUtil.isEmpty(id)){
            String[] accountIdList = id.split(",");
            for(String accountId: accountIdList){
                OauthAccount oauthAccount = oauthAccountService.getOauthAccountById(accountId);
                oauthAccount.setStatus(1);
                i=oauthAccountService.freezeAccount(oauthAccount);
            }
        }
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     * 解冻
     * @param id
     */
    @ApiOperation(value="解冻账户", notes="解冻账户")
    @DeleteMapping(value="/unfreeze/{id}")
    @Auth("/oauthAccount/unfreeze")
    public BaseResult unfreezeAccount(@PathVariable("id")String id){
        int i = 0;
        if(!StringUtil.isEmpty(id)){
            String[] accountIdList = id.split(",");
            for(String accountId: accountIdList){
                OauthAccount oauthAccount = oauthAccountService.getOauthAccountById(accountId);
                oauthAccount.setStatus(0);
                i=oauthAccountService.freezeAccount(oauthAccount);
            }
        }
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     * 查询账户集合
     * @param userParamInfo
     */
    @ApiOperation(value="查询账户集合", notes="查询账户集合")
    @PostMapping(value="/infoList")
    @Auth(value = "/oauthAccount/infoList",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult accountInfoList(@RequestBody UserParamInfo userParamInfo){
        Map<String, Object> condition = new HashMap<>();
        if(!StringUtil.isEmpty(userParamInfo.getAccount())){
            condition.put("account",userParamInfo.getAccount().split(","));
            List<OauthAccount> oauthAccountList = oauthAccountService.infoList(condition);
            List<UserInfoEntity> userInfoEntities = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(oauthAccountList)){
                for(OauthAccount oauthAccount:oauthAccountList){
                    UserInfoEntity userInfoEntity = new UserInfoEntity();
                    userInfoEntity.setAccount(oauthAccount.getAccount());
                    userInfoEntity.setName(oauthAccount.getName());
                    userInfoEntities.add(userInfoEntity);
                }
            }
            userParamInfo.setUserInfoEntities(userInfoEntities);
        }
        return new BaseResult(FastJsonUtils.toJSONString(userParamInfo));
    }

    /**
     * 重置密码
     * @param userParamInfo
     */
    @ApiOperation(value="重置密码", notes="重置密码")
    @PostMapping(value="/restPwd")
    public BaseResult updatePassword(@RequestBody UserParamInfo userParamInfo, HttpServletRequest request){
        int i  = oauthAccountService.restPwd(userParamInfo,request);
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     * 同步至授权中心
     * @param userInfoEntities
     */
    @PostMapping(value="/sync")
    @Auth(value = "/oauthAccount/sync",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    @ApiOperation(value="同步至授权中心", notes="同步至授权中心")
    public BaseResult syncOauth(@RequestBody List<UserInfoEntity> userInfoEntities){
        return oauthAccountService.sync(userInfoEntities);
    }

    /**
     * 根据账号查找单个账户
     * @param account
     */
    @ApiOperation(value="根据账号查找单个账户", notes="根据账号查找单个账户")
    @GetMapping(value="/single/{account}")
    @Auth(value = "/oauthAccount/single",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult<OauthAccount> getSingleOauthAccount(@PathVariable("account")String account){
        if(StringUtil.isEmpty(account)){
            return BaseResult.success();
        }
        OauthAccount oauthAccount = oauthAccountService.getSingleOauthAccount(account);
        return outDataStr(oauthAccount);
    }

    /**
     * 上传头像
     * @param request
     * @return
     */
    @PostMapping(value = "/pic/upload")
    @Auth(value = "/oauthAccount/pic/upload",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    @ApiOperation(value="上传头像", notes="上传头像")
    public BaseResult<OauthAccount> uploadMyPic(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//转型为MultipartHttpRequest：
        MultiValueMap<String, MultipartFile> multipartFileMultiValueMap =  multipartRequest.getMultiFileMap();//获取所有文件
        MultipartFile multipartFile = multipartRequest.getFile("userPicFile");//获取指定文件即前端file框name标签
        String account = getCurrentAccount();
        if(!StringUtil.isEmpty(account)){
            OauthAccount oauthAccount = oauthAccountService.getSingleOauthAccount(account);
            String pic = null;
            if(null != multipartFile && null != oauthAccount){
                try {
                    pic = Base64Util.toBase64(multipartFile.getBytes());
                    oauthAccount.setSmallPic(pic);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
                int i = oauthAccountService.updateSmallPic(oauthAccount);
                if(i>0){
                    return BaseResult.success(oauthAccount);
                }
            }
        }
        return BaseResult.fail();
    }

    /**
     * 注册账户
     * @param oauthAccount
     */
    @ApiOperation(value="注册账户", notes="注册账户根据相关资料")
    @PostMapping(value="/reg")
    public BaseResult regOauthAccount(@RequestBody OauthAccount oauthAccount){
        return oauthAccountService.regOauthAccount(oauthAccount);
    }
}
